<template>
  <vxe-modal
    :title="$t('common.action.update', '修改')"
    v-model="show"
    :loading="loading"
    :mask="false"
    :lock-view="false"
    width="800px"
    height="580px"
    destroy-on-close
    show-zoom
    remember
    resize
    show-footer
  >
    <el-form
      ref="refForm"
      :model="formData"
      :rules="formRules"
      label-width="120px"
    >
      <!-- name -->
      <el-form-item-plus
        :label="$t('menu.admin.role.field.name', '名称')"
        prop="name"
      >
        <el-input v-model="formData.name" placeholder="请输入名称" />
      </el-form-item-plus>

      <!-- code -->
      <el-form-item-plus
        :label="$t('menu.admin.role.field.code', '代码')"
        prop="code"
      >
        <el-input
          v-model="formData.code"
          :placeholder="$p('menu.admin.role.field.code', '代码')"
        />
      </el-form-item-plus>

      <!-- scope -->
      <el-form-item-plus
        :label="$t('menu.admin.role.field.scope', '数据权限')"
        prop="scope"
      >
        <ra-dict-select
          v-model="formData.scope"
          code="data_permission_options"
        ></ra-dict-select>
      </el-form-item-plus>

      <!-- dept_ids -->
      <el-form-item-plus
        :label="$t('menu.admin.role.field.dept_ids', '自定义部门')"
        prop="dept_ids"
        v-if="
          formData.scope ==
          PermissionEnum.data_permission_options_SPECIFIED_DEPT
        "
      >
        <ra-dict-select
          v-model="formData.scope"
          code="usr_dept_tree_options"
          type="cascade"
          multiple
        ></ra-dict-select>
      </el-form-item-plus>

      <!-- remark -->
      <el-form-item-plus
        :label="$t('common.field.remark', '备注')"
        prop="remark"
      >
        <el-input
          type="textarea"
          v-model="formData.remark"
          :placeholder="$p('common.field.remark', '备注')"
        />
      </el-form-item-plus>

      <!-- status -->
      <el-form-item-plus
        :label="$t('common.field.status', '状态')"
        prop="status"
      >
        <ra-dict-select
          v-model="formData.status"
          code="status_options"
          type="radio"
        />
      </el-form-item-plus>

      <!-- sort -->
      <el-form-item-plus :label="$t('common.field.sort', '排序号')" prop="sort">
        <el-input-number
          v-model="formData.sort"
          controls-position="right"
          :min="0"
        />
      </el-form-item-plus>
    </el-form>

    <template #footer>
      <el-button type="warning" @click="handleCancel">
        {{ $t('common.action.cancel', '取消') }}
      </el-button>
      <el-button type="info" @click="handleReset">
        {{ $t('common.action.reset', '重置') }}
      </el-button>
      <el-button type="primary" @click="handleSubmit" :disabled="loading">
        {{ $t('common.action.confirm', '确定') }}
      </el-button>
    </template>
  </vxe-modal>
</template>

<script setup>
import { smartTranslate as $t, transPlaceholder as $p } from '@/lang';
import { PermissionEnum } from '@/enums';
import { clone } from 'xe-utils';

defineOptions({
  name: 'EditUser',
  inheritAttrs: false,
});

const props = defineProps({
  api: {
    type: Object,
    required: true,
    validator: (value) => {
      return (
        typeof value.update === 'function' &&
        typeof value.getFormData === 'function'
      );
    },
  },
  options: {
    type: Object,
    default: () => ({}),
  },
});

const emit = defineEmits(['reload']);

// 响应式数据
const loading = ref(false);
const show = ref(false);
const activeName = ref('first');
const refForm = ref();
const currentId = ref(null);

// 表单数据
const formData = ref({
  id: null,
  name: null,
  code: null,
  scope: null,
  dept_ids: null,
  remark: null,
  status: 1,
  sort: null,
});

// 表单验证规则
const formRules = reactive({
  name: [
    {
      required: true,
      message: $p('menu.admin.role.field.name', '名称'),
      trigger: 'blur',
    },
  ],
  code: [
    {
      required: true,
      message: $p('menu.admin.role.field.code', '代码'),
      trigger: 'blur',
    },
  ],
});

// 重置表单
const resetForm = () => {
  refForm.value?.resetFields();
  Object.assign(formData.value, {
    id: null,
    name: null,
    code: null,
    scope: null,
    dept_ids: null,
    remark: null,
    status: 1,
    sort: null,
  });
};

// 加载用户数据
const loadUserData = async (id) => {
  loading.value = true;
  try {
    const { data } = await props.api.getFormData({ id });
    Object.assign(formData.value, data);
    currentId.value = id;
    await nextTick();
    refForm.value?.clearValidate();
  } catch (error) {
    console.error('Error loading data:', error);
    throw error;
  } finally {
    loading.value = false;
  }
};

// 提交处理
const handleSubmit = async () => {
  try {
    await refForm.value.validate();
    loading.value = true;

    const postData = clone(formData.value);
    console.log('Update Data:', postData);

    await props.api.update(postData);

    resetForm();
    show.value = false;
    emit('reload');
  } catch (error) {
    console.error('Error in edit operation:', error);
  } finally {
    loading.value = false;
  }
};

// 取消处理
const handleCancel = () => {
  resetForm();
  show.value = false;
};

// 重置处理
const handleReset = async () => {
  if (currentId.value) {
    await loadUserData(currentId.value);
  } else {
    resetForm();
  }
};

// 显示模态框
const showModal = async (id) => {
  if (!id) {
    console.error('User ID is required for edit mode');
    return;
  }

  try {
    await loadUserData(id);
    show.value = true;
  } catch (error) {
    console.error('Failed to load user data:', error);
  }
};

defineExpose({
  show: showModal,
});
</script>

<style lang="scss" scoped>
.form-section {
  margin: 5px;
  border: 1px solid #dcdfe6;
  padding: 5px;
  border-radius: 4px;
}
</style>
